<template>
    <div>
        <!-- 菜单管理 -->
        <el-form v-if="showSearch" :model="params">
            <el-row :gutter="20">
                <el-col :span="6">
                    <el-form-item label="菜单名称" :class="{ 'bold-label': true }">
                        <el-input v-model="params.menuName" placeholder="请输入菜单名称" clearable />
                    </el-form-item>
                </el-col>
                <el-col :span="4">
                    <el-form-item label="状态" :class="{ 'bold-label': true }">
                        <el-select clearable v-model="params.status" placeholder="菜单状态">
                            <el-option label="正常" value="0" />
                            <el-option label="停用" value="1" />
                        </el-select>
                    </el-form-item>
                </el-col>
                <el-col :span="12">
                    <el-button :icon="Search" type="primary" @click="SearchMaterialType">搜索</el-button>
                    <el-button :icon="Refresh" type="primary" plain @click="paramsReset">重置</el-button>
                </el-col>
            </el-row>
        </el-form>

        <!-- 按钮组 -->
        <el-row class="button-group">
            <el-col :span="10">
                <div>
                    <el-button type="primary" :icon="Plus" plain @click=handleaddW>新增</el-button>
                    <el-button type="info" plain :icon="Sort" @click="handleUnfold">展开/折叠</el-button>
                </div>
            </el-col>
            <el-col :span="14">
                <div class="button-right">
                    <el-tooltip content="隐藏搜索" placement="top">
                        <el-button :icon="Search" circle @click="toggleSearch" />
                    </el-tooltip>
                    <el-tooltip content="刷新" placement="top">
                        <el-button :icon="Refresh" circle @click="Reload" />
                    </el-tooltip>
                </div>
            </el-col>
        </el-row>

        <!-- 表格部分 -->
        <el-row>
            <el-table :data="tableData" row-key="menuId" :default-expand-all="isUnfold"
                :expand-row-keys="expandedRowKeys">
                <el-table-column prop="menuName" label="菜单名称" show-overflow-tooltip />
                <el-table-column prop="icon" label="图标" />
                <el-table-column prop="orderNum" label="排序" align="center" />
                <el-table-column prop="perms" label="权限标识" align="center" show-overflow-tooltip />
                <el-table-column prop="component" label="组件路径" align="center" show-overflow-tooltip />
                <el-table-column prop="status" label="状态" align="center">
                    <template #default="scope">
                        <el-tag :type="scope.row.status === '0' ? 'primary' : 'danger'">
                            {{ scope.row.status === '0' ? '正常' : '停用' }}
                        </el-tag>
                    </template>
                </el-table-column>
                <el-table-column prop="createTime" label="创建时间" align="center" width="200px" />
                <el-table-column width="253px" label="操作" align="center">
                    <template #default="scope">
                        <el-button class="btn_m" plain type="primary" text size="small" :icon="EditPen"
                            @click="handleupdate(scope.$index, scope.row)">修改</el-button>
                        <el-button class="btn_m" plain type="primary" text size="small" :icon="Plus"
                            @click="handleadd(scope.$index, scope.row)">新增</el-button>
                        <el-button class="btn_m" plain type="primary" text size="small" :icon="Delete"
                            v-show="scope.row.parentId !== 0"
                            @click="handleDelete(scope.$index, scope.row)">删除</el-button>
                    </template>
                </el-table-column>
            </el-table>
        </el-row>


        <addDialog :addDialog="dialogVisibleAdd" :id="menusAdd" :treeData="treeData" @close-dialog="colseDialog" />
        <updateDialog :updateDialog="dialogVisibleUpdate" :form="menusUpdate" :treeData="treeData"
            @close-dialog="colseDialog" />
    </div>
</template>

<script setup>
import addDialog from '@/components/MenuManagement/addDialog.vue';
import updateDialog from '@/components/MenuManagement/updateDialog.vue';
import { ref, onMounted, nextTick, computed, reactive } from 'vue'
import { Search, Refresh, Sort, Plus, EditPen, Delete } from '@element-plus/icons-vue'
import { findMenuList, deleteMenuId } from '@/apis/lth/index'
import { ElMessage, ElMessageBox } from "element-plus";
// 搜索参数
const params = ref({
    menuName: '',
    status: null
})
const tableData = ref([]) // 表格数据
const isUnfold = ref(false) // 默认是否展开
const expandedRowKeys = ref([]) // 存储展开行
const dialogVisibleAdd = ref(false) // 添加弹窗显示
const dialogVisibleUpdate = ref(false) // 修改弹窗显示

const colseDialog = () => {
    dialogVisibleAdd.value = false
    dialogVisibleUpdate.value = false
    menusAdd.menuId = ''
    initData()
}
//添加数据（默认值色设置）
let menusAdd = reactive({ menuId: '' })
let menusUpdate = ref({})
const treeData = ref([]);//菜单数据

function initData() {
    findMenuList(params.value).then(res => {
        tableData.value.length = 0
        Object.assign(tableData.value, res)
    })
    //查询的菜单列表
    findMenuList().then(res => {
        treeData.value.length = 0
        Object.assign(treeData.value, res)
    })
}

// 页面加载完成后执行
onMounted(async () => {
    initData()
})
/**
 * 搜索菜单
 */
const SearchMaterialType = async () => {
    if (params.value.status == undefined) {
        params.value.status = null
    }
    try {
        initData()
    } catch (error) {
        console.error('Failed to search menu type:', error);
    }
}
/**
 * 处理 展开/折叠
 */
const handleUnfold = () => {
    if (isUnfold.value) {
        expandedRowKeys.value = []
    } else {
        expandedRowKeys.value = tableData.value
    }
    isUnfold.value = !isUnfold.value
}

//隐藏搜索条件
const showSearch = ref(true);
const toggleSearch = () => {
    showSearch.value = !showSearch.value;
}
//刷新
const Reload = async () => {
    initData();
}

/**
 * 新增菜单，弹窗显示层(无指定添加)
 * @param index 
 * @param row 
 */
const handleaddW = (index, row) => {
    dialogVisibleAdd.value = true
}

/**
 * 新增菜单，弹窗显示层
 * @param index 
 * @param row 
 */
const handleadd = (index, row) => {
    dialogVisibleAdd.value = true
    menusAdd.menuId = row.menuId
}

/**
 * 修改菜单，弹窗显示层
 * @param index 行索引
 * @param row 行数据
 */
const handleupdate = (index, row) => {
    dialogVisibleUpdate.value = true
    Object.assign(menusUpdate.value, row)
}

/**
 * 删除菜单
 * @param index 行索引
 * @param row 行数据
 */
const handleDelete = async (index, row) => {
    ElMessageBox.confirm(`是否确认删除名称为${row.menuName}的数据项？`, '系统提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
    }).then(async () => {
        if (row.children == null) {
            await deleteMenuId(row.menuId)
            initData();
            ElMessage.success("删除成功")
            return
        }
        ElMessage.error("存在下级菜单，不允许删除")
    })
}

/**
 * 重置搜索参数
 */
const paramsReset = () => {
    params.value = {
        menuName: '',
        status: null
    }
    initData()
}
</script>

<style scoped>
::v-deep .dialogs {
    padding: 30px 20px
}

.row {
    width: 120px;
}

.dividing-line {
    text-align: center;
}

.button-right {
    text-align: right;
}

.button-group {
    margin-top: 20px;
    margin-bottom: 10px;
}

.demo-pagination-block .el-pagination {
    justify-content: end;
    margin-top: 20px;
}


/* 使用 ::v-deep 选择器 */
::v-deep .el-table .el-table__header-wrapper thead tr th {
    background-color: #f8f8f9 !important;
    /* 你可以根据需要更改颜色 */
    color: #515a6e !important;
    /* 文字颜色 */
}

/* 如果需要更具体的控制，可以使用更详细的类名 */
::v-deep .el-table .el-table__header-wrapper thead tr th,
::v-deep .el-table .el-table__body-wrapper tbody tr td {
    padding-left: 0 !important;
    /* 移除左边距 */
}

/* 使用 ::v-deep 选择器来穿透作用域样式 */
::v-deep .el-table th,
::v-deep .el-table td {
    padding-left: 0 !important;
    /* 移除左边距 */
}

::v-deep .bold-label .el-form-item__label {
    font-weight: bold !important;
}
</style>
